package cn.edu.stu.syllabus.switcher;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.AppCompatDelegate;

import cn.edu.stu.syllabus.application.SyllabusApplication;

/**
 * Created by daidaijie on 2016/12/31.
 */

public class DayNightSwitcher {

    private static final String TAG = "DayNightSwitcher";

    private static final String EXTRA_IS_NIGHT_MODE = "getIsNightMode";

    private SharedPreferences mSharedPreferences;

    private SharedPreferences.Editor mEditor;

    private boolean mIsNightMode;

    private DayNightSwitcher() {
        mSharedPreferences = SyllabusApplication.getContext()
                .getSharedPreferences(TAG, Context.MODE_PRIVATE);
        mEditor = mSharedPreferences.edit();
        mIsNightMode = getIsNightMode();
    }

    private static class DayNightSwitcherHolder {
        private static DayNightSwitcher sInstance = new DayNightSwitcher();
    }

    public static DayNightSwitcher getInstance() {
        return DayNightSwitcherHolder.sInstance;
    }

    private void setIsNightMode(boolean isNightMode) {
        mIsNightMode = isNightMode;
        mEditor.putBoolean(EXTRA_IS_NIGHT_MODE, isNightMode);
        mEditor.commit();
    }

    private boolean getIsNightMode() {
        return mSharedPreferences.getBoolean(EXTRA_IS_NIGHT_MODE, false);
    }

    public boolean isNightMode() {
        return mIsNightMode;
    }

    @AppCompatDelegate.NightMode
    private int getCurrentMode() {
        return mIsNightMode ? AppCompatDelegate.MODE_NIGHT_YES : AppCompatDelegate.MODE_NIGHT_NO;
    }

    public void switchActMode(AppCompatActivity appCompatActivity) {
        setIsNightMode(!mIsNightMode);
        AppCompatDelegate.setDefaultNightMode(getCurrentMode());
        Intent intent = new Intent(appCompatActivity, appCompatActivity.getClass());
        appCompatActivity.startActivity(intent);
        appCompatActivity.finish();
        appCompatActivity.overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
    }

    public void initAppMode() {
        AppCompatDelegate.setDefaultNightMode(getCurrentMode());
    }

}
